//
//  HMStatusDAL.swift
//  webo
//
//  Created by apple on 2016/11/26.
//  Copyright © 2016年 apple. All rights reserved.
//

import UIKit
import SVProgressHUD
private let expires_date_timeinterval: Double = -60*60*24*7
class HMStatusDAL: NSObject {
    //首页加载数据迁移
    class func homeLoadData(sinceId: Int64,maxId: Int64,finished: @escaping ([[String : Any]]?) -> ()) {
        let res = checkoutStatus(sinceId: sinceId, maxId: maxId)
        
        if let result = res, result.count > 0{
            //          finished(result)
            finished(result)
            return
        }
//        SVProgressHUD
    SVProgressHUD.show()
        //没有缓存数据则网络请求
        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
        let parameter = ["access_token" : HMUserAccountViewModel.shared.access_token,
                         "max_id" : "\(maxId)",
            
            "since_id" : "\(sinceId)"]
        //        print(parameter)
        
        HMNetworkingTools.shared.request(method: .GET, urlString: urlString, parameter: parameter){(object,error) -> () in
            
            if (error != nil) {
                finished(nil)
                SVProgressHUD.dismiss()
                NotificationCenter.default.post(name: NSNotification.Name(visitNetworkFaile), object: "visitNetworkFaile")
                return
            }
            //        print(object)
            let dic = object as! [String : Any]
            SVProgressHUD.dismiss()
            //阻塞
            guard  let arr = dic["statuses"] as? [[String : Any]] else{
                finished(nil)
                return
            }
            finished(arr)
            chacheStatus(array: arr)
        }
    }
    
    //监测数据
    class func checkoutStatus(sinceId: Int64,maxId: Int64) -> [[String : Any]]?{
        //        判断是否登录
        guard let userId = HMUserAccountViewModel.shared.userAccount?.uid else {
            print("还没有登入")
            return nil
        }
        
        var sql = "SELECT status FROM T_Status WHERE userId = \(userId) "
        
        if sinceId > 0 {
            sql += "AND statusId > \(sinceId)"
        }
        if maxId > 0{
            sql += "AND statusId < \(maxId)"
        }
        sql += "ORDER BY statusId DESC "
        sql += "LIMIT 20"
        var array = [[String : Any]]()
        HMSQLiteTool.shared.queue.inDatabase { (db) in
            guard let res = db!.executeQuery(sql, withArgumentsIn: nil)else{
                return
            }
            while res.next(){
                let jsonData = res.data(forColumn: "status")
                let dict = try! JSONSerialization.jsonObject(with: jsonData!, options: [])
                array.append(dict as! [String : Any])
            }
        }
        return array
    }
    
    
    
    //4. 获取网络数据之后就应该立即存储网络数据
    /*
     statusId
     status
     userId
     */
    class func chacheStatus(array: [[String:Any]]) {
        guard let userid  = HMUserAccountViewModel.shared.userAccount?.uid else {
            print("还没有登录呢")
            return
        }
        let sql = "INSERT OR REPLACE INTO T_Status (statusId,status,userId) VALUES (?,?,?)"
        HMSQLiteTool.shared.queue.inTransaction { (db, rollBack) in
            
            for item in array{
                let statusId = item["id"]!
                //数据库中能够存储的数据不能够是Foundation 需要将字典数据转换二进制数据存储到数据库中
                //如果是字典数据 在读取的时候会有问题
                let jsonData = try! JSONSerialization.data(withJSONObject: item, options: [])
                let res = db!.executeUpdate(sql, withArgumentsIn: [statusId,jsonData,userid])
                
                if !res{
                    //不成功就回滚
                    rollBack?.pointee = true
                    return
                }
            }
        }
    }
    
    class func clearCacheStatus() {
        let exprise_date = Date(timeIntervalSinceNow:expires_date_timeinterval)
//        let sharedDateformata = DateFormatter()
        sharedDateformata.locale = Locale(identifier: "en")
        sharedDateformata.dateFormat = "yyyy-MM-dd HH:mm:ss"
        let dateStr = sharedDateformata.string(from: exprise_date)
        let sql = "DELETE FROM T_Status WHERE create_date < ?"
        HMSQLiteTool.shared.queue.inTransaction { (db, rollBack) in
            let res = db!.executeUpdate(sql, withArgumentsIn: [dateStr])
            if !res{
                
            rollBack?.pointee = true
            }
        }
        
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }

}


//}

